//
//  JingxuanViewController.m
//  HomeIn
//
//  Created by dllo on 15/11/5.
//  Copyright © 2015年 ZZP. All rights reserved.
//

#import "JingxuanViewController.h"
#import "CycleModel.h"
#import "FirstPageModel.h"
#import "CycleViewController.h"
#import "JingxuanCell.h"
#import "DetailViewController.h"

@interface JingxuanViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,SDCycleScrollViewDelegate>

@property (nonatomic, retain) UICollectionView *collectionView;

@property (nonatomic, retain) NSMutableArray *cycleModelArray;//轮播图数组
@property (nonatomic, retain) NSMutableArray *pictureArray;//轮播图图片数组
@property (nonatomic, retain) NSMutableArray *modelArray;//model数组

@property (nonatomic, assign) NSInteger currentPage;//记录当前page
@property (nonatomic, assign) BOOL isUpLoading;//标记是否为上拉

@property (nonatomic, retain) MBProgressHUD *HUB;//菊花

@property (nonatomic, assign) int n;//全局变量

@end

@implementation JingxuanViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //视图将要出现的时候刷新
    [self.collectionView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //默认n为0
    self.n = 0;
    
    self.pictureArray = [NSMutableArray array];
    self.cycleModelArray = [NSMutableArray array];
    self.modelArray = [NSMutableArray array];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(WIDTH - 20, HEIGHT / 4);
    //设置item的行间距
    flowLayout.minimumLineSpacing = 10;
    //设置item的上,左,下,右 边界距离
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    //头部区域大小
    flowLayout.headerReferenceSize = CGSizeMake(WIDTH, HEIGHT / 4);
    //底部区域大小
    flowLayout.footerReferenceSize = CGSizeMake(WIDTH, 49);
    //滑动方向
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    //collectionView
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 30) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.collectionView];
    //注册cell
    [self.collectionView registerClass:[JingxuanCell class] forCellWithReuseIdentifier:@"reuse"];
    //注册表头和底部视图
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerView"];
    
    //活动指示器(菊花)
    self.HUB = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.HUB show:YES];
    self.HUB.labelText = @"正在加载";
    
    self.currentPage = 20;//默认请求下来的数据为第20页
    self.isUpLoading = NO;//默认是下拉状态
    [self getAFNetWorkingDataForCycle];//请求轮播图数据
    [self getAFNetWorkingData:self.currentPage];//请求cell数据
    [self addHeaderRefresh];
    [self addFooterRefresh];
}

//下拉刷新
- (void)addHeaderRefresh
{
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        self.isUpLoading = NO;//标记为下拉
        NSLog(@"下拉");
        self.currentPage = 0;//刷新首页,只要下拉,就请求第0页数据
        //重新请求数据
        [self getAFNetWorkingDataForCycle];
        [self getAFNetWorkingData:self.currentPage];
    }];
    
    // 马上进入刷新状态
    [self.collectionView.header beginRefreshing];
}

//上拉刷新
- (void)addFooterRefresh
{
    
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        
        self.isUpLoading = YES;//标记为上拉
        NSLog(@"上拉");
        self.currentPage+=20;//上拉一次,页码+20
        
        [self getAFNetWorkingData:self.currentPage];
    }];
   
}

- (void)getAFNetWorkingDataForCycle
{
    //接⼝
    NSString *urlString = @"http://api.bohejiaju.com/v1/banners?channel=iOS";
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //下拉时,删除之前的,存入最新的数据
        if (self.isUpLoading == NO)
        {
            //如果是下拉刷新,清空数组
            [self.cycleModelArray removeAllObjects];
            [self.pictureArray removeAllObjects];

        }
        
        NSMutableDictionary *dictionary = responseObject;
        NSMutableArray *array = [[dictionary objectForKey:@"data"] objectForKey:@"banners"];
        
        //轮播图
        for (NSMutableDictionary *dic in array) {
            
            [self.pictureArray addObject:[dic objectForKey:@"image_url"]];
            
        }
        
        for (NSMutableDictionary *dic in array)
        {

            CycleModel *cycleModel = [[CycleModel alloc] init];
            [cycleModel setValuesForKeysWithDictionary:dic];
            
            //将title取出
            cycleModel.title = [[dic objectForKey:@"target"] objectForKey:@"title"];
            [self.cycleModelArray addObject:cycleModel];

            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSArray *fileArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentPath = [fileArray lastObject];
            NSString *archivePath = [documentPath stringByAppendingPathComponent:@"lunbo"];
            BOOL relust1 = [fileManager removeItemAtPath:archivePath error:nil];
            //NSLog(@"==== %@",archivePath);
            if (relust1) {
                NSLog(@"沙盒文件删除成功");
            }else
            {
                NSLog(@"沙盒文件删除失败");
            }
            BOOL relust4 =  [NSKeyedArchiver archiveRootObject:responseObject toFile:archivePath];
            if (relust4) {
                NSLog(@"归档成功");
            }else
            {
                NSLog(@"归档失败");
            }

        }
        
        

        [self.collectionView reloadData];
        
        //数据出现,即页面显示,则菊花消失
        //[self.HUB hide:YES];
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
             NSLog(@"error = %@",error);
             
         }];
  
}


- (void)getAFNetWorkingData:(NSInteger)page
{
    
    NSString *urlString = [NSString stringWithFormat:@"http://api.bohejiaju.com/v1/channels/6/items?gender=1&generation=2&limit=20&offset=%ld", self.currentPage];
    
    //[NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];  代表支持所有的接口类型
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        //下拉时,删除之前的,存入最新的数据
        if (self.isUpLoading == NO)
        {
            //如果是下拉刷新,清空数组
            [self.modelArray removeAllObjects];
            
//            //有网时候,删除数据库中已保存的本地数据(否则会不停重复储存数据)
//            //用户第一次使用本APP是不会删除的
//            NSMutableArray *array = [[DataBaseHandle ShareDataBaseHandle] selectSelectionTable];
//            for (SelectionModel *selectionModel in array)
//            {
//                [[DataBaseHandle ShareDataBaseHandle] deleteSelectionTable:selectionModel.title];
//            }
            
        }
        //上拉刷新,则往数组里增加,页面上也增加
        NSMutableDictionary *dictionary = responseObject;
        NSMutableArray *array = [[dictionary objectForKey:@"data"] objectForKey:@"items"];
        
        for (NSMutableDictionary *dic in array)
        {
            FirstPageModel *firstPageModel = [[FirstPageModel alloc] init];
            [firstPageModel setValuesForKeysWithDictionary:dic];
            
            [self.modelArray addObject:firstPageModel];
            
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSArray *fileArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentPath = [fileArray lastObject];
            NSString *archivePath = [documentPath stringByAppendingPathComponent:@"jingxuan"];
            BOOL relust1 = [fileManager removeItemAtPath:archivePath error:nil];
            //NSLog(@"==== %@",archivePath);
            if (relust1) {
                NSLog(@"沙盒文件删除成功");
            }else
            {
                NSLog(@"沙盒文件删除失败");
            }
            BOOL relust4 =  [NSKeyedArchiver archiveRootObject:responseObject toFile:archivePath];
            if (relust4) {
                NSLog(@"归档成功");
            }else
            {
                NSLog(@"归档失败");
            }
        }
        
        //结束下拉上拉刷新
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        
        //刷新
        [self.collectionView reloadData];
        
        //数据出现,即页面显示,则菊花消失
        [self.HUB hide:YES];
    }
         failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             
             //让菊花停留1s之后,显示手机本地缓存数据
             [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(errorInfo1) userInfo:nil repeats:NO];
             
             self.HUB.labelText = @"网络请求失败,请检查网络";
             
             NSLog(@"error = %@",error);
             
         }];

}

-(void)errorInfo1
{
    //离线时,取出本地表中的数据
//    NSArray *fileArray1 =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *documentPath1 = [fileArray1 lastObject];
//    NSString *archivePath1 = [documentPath1 stringByAppendingPathComponent:@"jingxuan"];
//    NSMutableDictionary *data = [NSKeyedUnarchiver unarchiveObjectWithFile:archivePath1];
    
    
    [self.collectionView.header endRefreshing];
    [self.collectionView.footer endRefreshing];
    
    [self.collectionView reloadData];
    [self.HUB hide:YES];
    
}

//设置表头和底部内容
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (kind == UICollectionElementKindSectionHeader)
    {
        //表头是焦点图和四个图标
        UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        
        //避免不停叠加
        if (self.n > 0)
        {
            //删除子视图,保留父视图
            for (SDCycleScrollView *cycleScrollView in reusableView.subviews)
            {
                if ([cycleScrollView isKindOfClass:[SDCycleScrollView class]])
                {
                    [cycleScrollView removeFromSuperview];
                }
            }

            //轮播图
            SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 4) imageURLStringsGroup:nil];
            // 设置pageControl居右，默认居中
            cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
            cycleScrollView.delegate = self;
            //图片数组
            cycleScrollView.imageURLStringsGroup = self.pictureArray;
            // 自定义轮播时间间隔
            cycleScrollView.autoScrollTimeInterval = 5.0;
            [reusableView addSubview:cycleScrollView];
        }
        self.n++;//累加
        return  reusableView;

    } else {
        UICollectionReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footerView" forIndexPath:indexPath];
        
        return reusableView;
    }
    
}

//轮播图三方的点击事件
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    CycleViewController *cycleVC = [[CycleViewController alloc] init];
    CycleModel *cycleModel = [self.cycleModelArray objectAtIndex:index];
    cycleVC.cycleModel = cycleModel;
    
    cycleVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:cycleVC animated:YES];
    
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.modelArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //直接从cell重用池里取
    JingxuanCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    
    cell.layer.masksToBounds = YES;//masksToBounds裁剪掉边框
    cell.layer.cornerRadius = 5;//设置圆角度
    
    FirstPageModel *firstPageModel = [self.modelArray objectAtIndex:indexPath.row];
    cell.firstPageModel = firstPageModel;
    
    return cell;
    
}

//点击item触发方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    FirstPageModel *firstPageModel = [self.modelArray objectAtIndex:indexPath.row];
    detailVC.firstPageModel = firstPageModel;//属性传值

    //push到详情的时候让tabBar(工具栏)消失
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];


}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
